package cn.tedu.charging.order.config;

import cn.tedu.charging.order.dao.repository.OrderRepository;
import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.service.OrderService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mqtt 客户端配置
 */
@Configuration
public class MqttConfig {

    /**
     * 用户名
     */
    private String username = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 地址 连接的默认端口号 1883
     */
    private String host = "tcp://localhost:1883";

    /**
     * 客户端id
     */
    private String clientId = "order_service_client";

    private MqttClient mqttClient;

    @Autowired
    private OrderRepository orderRepository;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        //通过链接地址和客户端id进行连接
        //客户端id的目的是告诉我们的服务器,谁在链接它
        mqttClient = new MqttClient(host, clientId);

        //连接相关的配置
        MqttConnectOptions connOpts = new MqttConnectOptions();
        //用户名
        connOpts.setUserName(username);
        //密码
        connOpts.setPassword(password.toCharArray());
        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        connOpts.setCleanSession(true);
        //创建mqtt消费者
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,orderRepository);
        //设置消费者
        mqttClient.setCallback(mqttConsumer);

        //基于上面配置号的连接相关的配置,进行连接
        mqttClient.connect(connOpts);

        //返回连接客户端
        return mqttClient;

    }
}
